<template>
  <div class="order-detail-container">
    <div v-if="order" class="order-detail">
      <div class="order-header">
        <h1>{{ order.title }}</h1>
        <div class="order-status" :class="order.status">
          {{ statusMap[order.status] }}
        </div>
      </div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      <div class="order-info">
        <div class="order-type-price">
          <p class="order-type">{{ typeMap[order.type] }}</p>
          <p class="order-price">¥{{ order.price }}</p>
        </div>
        <div class="order-locations">
          <div class="location-item">
            <h3>取货地点</h3>
            <p>{{ order.pickup_location }}</p>
          </div>
          <div class="location-item">
            <h3>送货地点</h3>
            <p>{{ order.delivery_location }}</p>
          </div>
        </div>
        <div class="order-description">
          <h3>订单描述</h3>
          <p>{{ order.description }}</p>
        </div>
      </div>
      <div class="order-participants" v-if="order.status !== 'pending'
          && order.status !== 'cancelled'">
        <div v-if="order.requester" class="participant-item">
          <h3>发起者</h3>
          <div class="participant-info">
            <img :src="order.requester.avatar || '/default-avatar.png'" alt="用户头像">
            <div>
              <p>{{ order.requester.username }}</p>
              <p>{{ order.requester.phone }}</p>
            </div>
          </div>
        </div>
        <div v-if="order.runner" class="participant-item">
          <h3>跑腿员</h3>
          <div class="participant-info">
            <img :src="order.runner.avatar || '/default-avatar.png'" alt="跑腿员头像">
            <div>
              <p>{{ order.runner.username }}</p>
              <p>{{ order.runner.phone }}</p>
              <div class="runner-rating">
                <div class="stars">
                  <i v-for="i in 5" :key="i" :class="{ 'filled': i <= order.runner.rating }" class="fa-star"></i>
                </div>
                <span>{{ order.runner.rating }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="order-actions">
        <button v-if="isRequester && order.status === 'pending'" @click="cancelOrder()">取消订单</button>
        <button v-if="isRunner && (order.status === 'accepted' || order.status === 'processing')" @click="completeOrder()">完成订单</button>
        <button v-if="!isRequester && !isRunner && order.status === 'pending'" @click="acceptOrder()">接单</button>
      </div>
    </div>
    <div v-else-if="isLoading" class="loading">加载中...</div>
    <div v-else-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { errandApi } from '@/api'
import { getUserInfo } from '@/api/user'
import { formatDate } from '@/utils/date'

const route = useRoute()
const orderId = route.params.id
const order = ref(null)
const currentUser = ref(null)
const isLoading = ref(false)
const errorMessage = ref('')

// 订单类型映射
const typeMap = {
  'food': '外卖代拿',
  'express': '快递代取',
  'other': '其他代办'
}

// 订单状态映射
const statusMap = {
  'pending': '待接单',
  'accepted': '已接单',
  'processing': '进行中',
  'completed': '已完成',
  'cancelled': '已取消'
}

// 是否是发起者
const isRequester = computed(() => {
  return currentUser.value && order.value &&
         currentUser.value.id === order.value.requester.id
})

// 是否是跑腿员
const isRunner = computed(() => {
  return currentUser.value && order.value &&
         order.value.runner && currentUser.value.id === order.value.runner.id
})

// 获取订单详情
const fetchOrderDetail = async () => {
  isLoading.value = true
  errorMessage.value = ''
  try {
    const res = await errandApi.getOrderDetail(orderId)
    order.value = res.data
  } catch (error) {
    errorMessage.value = '获取订单详情失败，请稍后重试'
    console.error('获取订单详情失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    const res = await getUserInfo()
    currentUser.value = res.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 取消订单
const cancelOrder = async () => {
  try {
    await errandApi.cancelOrder(orderId)
    order.value.status = 'cancelled'
    ElMessage.success('订单已取消')
  } catch (error) {
    ElMessage.error('取消订单失败，请稍后重试')
    console.error('取消订单失败:', error)
  }
}

// 接单
const acceptOrder = async () => {
  try {
    await errandApi.acceptOrder(orderId)
    // 重新获取订单详情
    fetchOrderDetail()
    ElMessage.success('接单成功')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '接单失败，请稍后重试')
    console.error('接单失败:', error)
  }
}

// 完成订单
const completeOrder = async () => {
  try {
    await errandApi.completeOrder(orderId)
    order.value.status = 'completed'
    ElMessage.success('订单已完成')
  } catch (error) {
    ElMessage.error('完成订单失败，请稍后重试')
    console.error('完成订单失败:', error)
  }
}

// 页面加载时执行
onMounted(() => {
  fetchCurrentUser()
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.order-header h1 {
  font-size: 24px;
}

.order-status {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.order-status.pending {
  background-color: #f0f9eb;
  color: #67c23a;
}

.order-status.accepted {
  background-color: #ecf5ff;
  color: #4096ff;
}

.order-status.processing {
  background-color: #fffbe6;
  color: #e6a23c;
}

.order-status.completed {
  background-color: #f5f5f5;
  color: #909399;
}

.order-status.cancelled {
  background-color: #fef0f0;
  color: #f56c6c;
}

.order-info {
  margin-bottom: 30px;
}

.order-type-price {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.order-type {
  font-size: 16px;
  color: #666;
}

.order-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff7a45;
}

.order-locations {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.location-item {
  flex: 1;
  min-width: 250px;
}

.location-item h3,
.order-description h3,
.participant-item h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.location-item p,
.order-description p {
  color: #666;
}

.participant-item {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.participant-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.participant-info img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.runner-rating {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.stars {
  margin-right: 6px;
  color: #e6a23c;
}

.stars .filled {
  fill: #e6a23c;
}

.order-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.order-actions button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.order-actions button:nth-child(2) {
  background-color: #ff7a45;
}

.order-actions button:hover {
  opacity: 0.9;
}

.order-actions button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.error-message {
  color: #f56c6c;
  padding: 10px;
  background-color: #fef0f0;
  border-radius: 4px;
  margin-bottom: 20px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}
</style>